const path = require('path')
const productModel = require(path.join(__dirname,"../model/productModel.js"))
const categoryModel = require(path.join(__dirname,"../model/categoryModel.js"))
const pagination = require(path.join(__dirname,"../utils/pagination.js"))
const querystring = require('querystring')

const isNumber = val => {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val) || regNeg.test(val)){
        return true
    }else{
        return false
    }
}

/**
 * 商品列表
 */
exports.index = (req,res) => {
    const cateId = req.params.cateId
    let page = req.query.page || 1
    // 判断非数字
    if (!isNumber(page)){
        page = 1
    }
    
    // 判断page的值是否小于1
    page = parseInt(page) < 1 ? 1 : page
    // 获取总页数
    const totalPage = req.query.totalPage
    if (totalPage) {
        // 判断临界值
        page = page > parseInt(totalPage) ? totalPage : page
    }
    const size = req.query.size || 10
    const sort = req.query.sort || 'commend'

    Promise.all([
        // 查询分类下的商品列表
        productModel.getCateProducts(cateId,page,size,sort),
        // 查询分类的上级&上上级分类
        categoryModel.getCategoryParent(cateId)
    ]).then(results=>{
        // 设置列表需要渲染的值
        res.locals.list = results[0].list
        res.locals.total = results[0].total
        res.locals.sort = sort
        res.locals.cate = results[1]

        // 渲染分页条
        res.locals.pagination = pagination({page:page,totalPage:results[0].total,req})

        // 渲染列表页面
        res.render(path.join(__dirname,"../views/list"))
    })
}

/**
 * 商品搜索
 */
exports.search = (req,res) => {
    const q = req.query.q || ''

    let page = req.query.page || 1
    // 判断非数字
    if (!isNumber(page)){
        page = 1
    }
    
    // 判断page的值是否小于1
    page = parseInt(page) < 1 ? 1 : page
    // 获取总页数
    const totalPage = req.query.totalPage
    if (totalPage) {
        // 判断临界值
        page = page > parseInt(totalPage) ? totalPage : page
    }
    const size = req.query.size || 10
    const sort = req.query.sort || 'commend'

    productModel.getSearchProducts(querystring.escape(q),page,size,sort).then(result=>{
        // 渲染列表页面需要的数据
        res.locals.q = q
        res.locals.sort = sort
        res.locals.list = result.list
        // 渲染分页条
        res.locals.pagination = pagination({page:page,totalPage:result.total,req})

        res.render(path.join(__dirname,"../views/list"))
    })
}   